/*
 * ECARX Technology Limited is the owner of the copyright and the trade secret of this software.
 * Without permission, no one has the right to obtain, disclose or use this software in any way.
 */

package com.ecarx.systemui.plugin;

import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;

import com.ecarx.systemui.plugin.utils.LogUtils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class PluginContext {

    private static final String TAG = "PluginContextUtilsTag";

    private static PluginContext pluginContext;

    //此Context 保存的是SystemUi传递的Context
    private Context mContext;

    private PluginContext(Context context) {
        this.mContext = context;
    }

    public static synchronized void initSavePluginContext(Context context) {
        if (pluginContext == null) {
            pluginContext = new PluginContext(context);
        }
    }

    public static PluginContext getInstance() {
        return pluginContext;
    }

    public Context getPluginContext() {
        return mContext;
    }

    private static Context hostAppContext;

    public static Context getContextByActThread() {
        if (hostAppContext == null) {
            try {
                @SuppressLint("PrivateApi")
                Class<?> activityThreadClass = Class.forName("android.app.ActivityThread");
                final Method method = activityThreadClass.getMethod(
                        "currentApplication");
                // 得到当前的Application 对象
                Application application = (Application) method.invoke(null);
                LogUtils.d(TAG, "getContextByActThread application:" + application);
                if (application != null) {
                    hostAppContext = application.getApplicationContext();
                    LogUtils.e(TAG, "getContextByActThread applicationContext:" + hostAppContext);
                }
            } catch (ClassNotFoundException | NoSuchMethodException |
                    IllegalAccessException | InvocationTargetException e) {
                LogUtils.e(TAG, "getContextByActThread ERROR :" + e);
            }
        }
        return hostAppContext;
    }

}
